//
// Created by 86138 on 2025/5/3.
//
#include "SqList.h"

void InitList(SqList &L) {
    L.Elem = (ElemType *) malloc(LIST_INIT_SIZE * sizeof(ElemType));
    if (!L.Elem) exit(OVERFLOW) ;

    L.Length = 0;
    L.List_Size = LIST_INIT_SIZE;
}

Status ListInsert(SqList &L, int i, ElemType e) {
    ElemType *newbase, *p, *q;
    if (i < 1 || i > L.Length + 1) {
        printf("错误的插入位置i\n");
        return ERROR;
    }
    if (L.Length == L.List_Size) {
        printf("顺序表已满，需要先扩容\n");
        newbase = (ElemType *) realloc(L.Elem, (L.List_Size + LIST_INCREMENT) * sizeof(ElemType));
        if (!newbase) exit(OVERFLOW);
        L.Elem = newbase;
        L.List_Size += LIST_INCREMENT;
    }

    q = L.Elem + i - 1; // q为插入位置
    for (p = L.Elem + L.Length - 1; p >= q; p--) {
        *(p + 1) = *p;
    }
    *q = e;

    /* 也可以已使用下面的代码段，效果一样 */
//    for (int j = L.Length - 1; j >= i - 1 ; j--) {
//        L.Elem[j + 1] = L.Elem[j];
//    }
//    L.Elem[i - 1] = e;
    L.Length++;
    return OK;
}

Status ListDelete(SqList &L, int i, ElemType &e) {
    ElemType *p, *q;
    if (i < 1 || i > L.Length) {
        printf("错误的删除位置i\n");
        return ERROR;
    }

    q = L.Elem + i - 1; // q是待删除元素位置
    e = *q;
    for (p = q; p <= L.Elem + L.Length - 1; p++) {
        *p = *(p + 1);
    }
    L.Length--;
    return OK;
}

void DestroyList(SqList &L) {
    free(L.Elem);
    L.Elem = NULL;
    L.Length = 0;
    L.List_Size = 0;
}

Status GetElem(SqList &L, int i, ElemType &e) {
    if (i < 1 || i > L.Length) {
        printf("错误的获取位置i\n");
        return ERROR;
    }
    e = *(L.Elem + i - 1);
    return OK;
}
